package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * String读写器以\0为结束字符 GBK编码
 * 
 * @author shenliuyang
 *
 *         2016年8月1日上午10:09:42
 */
public class StringFieldReaderWriter extends FieldReaderWriter {

	public StringFieldReaderWriter(Field field, int size, int order) {
		super(field, 0, order);
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		int c;
		List<Byte> byteList = new ArrayList<>();
		while ((c = in.read()) != '\0' && c != -1) {
			byteList.add((byte) c);
		}
		byte[] data = new byte[byteList.size()];
		for (int i = 0; i < data.length; i++) {
			data[i] = byteList.get(i);
		}
		String value = new String(data, "GBK");
		wrtietoField(to, value);
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		String value = (String) readFromField(from);
		if (StringUtils.isBlank(value)) {
			out.write('\0');
			return;
		}
		out.write(value.getBytes("GBK"));
		out.write('\0');
	}
}